import { useContext, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { BaseContext } from '../../context';

const Detail = () => {
  const { state } = useLocation();
  const [isEdit, setIsEdit] = useState(false);
  const [data, setData] = useState(state);
  const { tasks, setTasks } = useContext(BaseContext);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setData({
      ...data,
      [name]: value
    });
  };

  const handleSave = () => {
    const newTasks = tasks.map(item => item.id === data.id ? data : item);
    setTasks(newTasks);
  };

  return (
    <div>
      <h1>详情页</h1>
      <div>ID：{data.id}</div>
      <div>任务名称：{isEdit ? <input name="title" value={data.title} onChange={handleChange} /> : data.title}</div>
      <div>任务状态：{isEdit ? (
        <select
          name="state"
          value={data.state}
          onChange={handleChange}
        >
          <option value="">请选择任务状态</option>
          <option value="未开始">未开始</option>
          <option value="进行中">进行中</option>
          <option value="已完成">已完成</option>
        </select>
      ) : data.state}</div>
      <div>优先级：{isEdit ? (
        <select
          name="priority"
          value={data.priority}
          onChange={handleChange}
        >
          <option value="">请选择优先级</option>
          <option value={1}>1</option>
          <option value={2}>2</option>
          <option value={3}>3</option>
        </select>
      ) : data.priority}</div>
      <div>任务描述：{isEdit ? <textarea name="desc" onChange={handleChange} value={data.desc} /> : data.desc}</div>

      <button className="edit-button" onClick={() => setIsEdit(true)}>编辑</button>
      {isEdit && <button className="submit-button" onClick={handleSave}>保存</button>}
    </div>
  );
};

export default Detail;